<script setup lang="ts">
import { wxLogin } from "@/api/user/login";
import { ref } from "vue";
import { useUserStore } from "@/store/modules/user";
const userStore = useUserStore();
const code = ref<string>();
const emit = defineEmits(["success"]);
const getCode = () => {
  uni.login({
    success: (res) => {
      console.log(res);
      code.value = res.code;
    },
  });
};
getCode();
const getuserinfos = () => {
  uni.showLoading({
    title: "登录中",
  });
  uni.getUserProfile({
    desc: "展示用户信息", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
    success: (res) => {
      let data = {
        code: code.value,
        encryptedData: res.encryptedData,
        iv: res.iv,
        rawData: res.rawData,
        signature: res.signature,
        avatarUrl: res.userInfo.avatarUrl,
      };
      uni.setStorageSync("user", res.userInfo);
      wxLogin(data)
        .then((res) => {
          userStore.setToken(res.data.token);
          userStore.getuserInfo()
          uni.hideLoading();
          emit("success",res.data);
        })
        .catch(() => {
          code.value = "";
          getCode();
          uni.hideLoading();
        });
    },
    fail: (err) => {
      uni.hideLoading();
    },
  });
};
</script>

<template>
  <div @click="getuserinfos">
    <slot>
      <!--  #ifdef  MP-WEIXIN -->
      <button v-if="!userStore.getToken" type="success" class="dialog-login-btns">
        微信授权登录
      </button>

      <!-- #endif -->
    </slot>
  </div>
</template>

<style lang=""></style>
